﻿package {
	import flash.utils.*;
	import flash.ui.Mouse;
	import flash.display.MovieClip;
	import flash.display.Loader;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFieldAutoSize;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.DropShadowFilter;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	import flash.geom.Point;
	import flash.geom.ColorTransform;
	import fl.transitions.Tween;
	import fl.transitions.easing.*;
	import fl.transitions.TweenEvent;
	
	public class Portfolio extends MovieClip{
		private var shadowFilter:DropShadowFilter;
		private var library:Object;
		private var portfolioItens:Array;
		private var portPositions:Array;
		private var descContainers:Array;
		private var loadCounter:int;
		private var current:int;
		private var descIdentifier:Boolean;
		private var point0:Number;
		private var limitPoint:Number;
		private var chainLock:Number;
		private var xDragOffset:Number;
		private var sliderContainer:MovieClip;
		private var prevBt:MovieClip;
		private var nextBt:MovieClip;

		public function Portfolio() {
			portfolioItens = new Array();
			loadCounter = 0;
			shadowFilter = new DropShadowFilter(0, 0, 0, 1, 10, 10, 1, 3, false, false, false);
			portPositions = new Array(new Point(10, 94.15),
									  new Point(225, 94.15),
									  new Point(440, 10),
									  new Point(870, 94.15),
									  new Point(1085, 94.15));
			descContainers = new Array(new MovieClip(), new MovieClip());
		}
		
		public function preStart(_library:Object):void {
			library = _library;
			
			var pageTitle:MovieClip = new library.pageTitle;
			pageTitle.x = 525;
			pageTitle.filters = [shadowFilter];
			pageTitle.name = 'pageTitle';
			this.addChild(pageTitle);
			
			var pageHeaderFormat:TextFormat = new TextFormat();
			pageHeaderFormat.align = 'center';
			pageHeaderFormat.font = 'Arial';
			pageHeaderFormat.color = 0xffffff;
			pageHeaderFormat.size = 25;
			pageHeaderFormat.bold = true;
			var pageHeader:TextField = new TextField();
			pageHeader.defaultTextFormat = pageHeaderFormat;
			pageHeader.text = "Portfolio";
			pageHeader.width = pageTitle.width;
			pageHeader.y = 13;
			pageHeader.selectable = false;
			pageTitle.addChild(pageHeader);
		}
		
		public function start():void {
			var loadingGif:MovieClip = new library.loadingGif;
			loadingGif.name = 'loadingGif';
			loadingGif.x = 625;
			loadingGif.y = 275;
			this.addChild(loadingGif);
			
			for(var j:int = 0; j < descContainers.length; j++){
				var titleFormat:TextFormat = new TextFormat();
				titleFormat.font = 'Arial';
				titleFormat.size = 16;
				titleFormat.align = 'center';
				titleFormat.color = 0xcccccc;
				titleFormat.bold = true;
				var title:TextField = new TextField();
				title.defaultTextFormat = titleFormat;
				title.selectable = false;
				title.autoSize = TextFieldAutoSize.CENTER;
				title.width = 420;
				title.wordWrap = true;
				title.name = 'title';
				title.x = 0;
				descContainers[j].addChild(title);
				
				var descStyle:TextFormat = new TextFormat();
				descStyle.font = 'Arial';
				descStyle.size = 14;
				descStyle.align = 'center';
				descStyle.color = 0xffffff;
				var description:TextField = new TextField();
				description.defaultTextFormat = descStyle;
				description.selectable = false;
				description.autoSize = TextFieldAutoSize.CENTER;
				description.width = 420;
				description.wordWrap = true;
				description.name = 'description';
				description.x = 0;
				descContainers[j].addChild(description);
				
				var technology:TextField = new TextField();
				technology.defaultTextFormat = descStyle;
				technology.selectable = false;
				technology.autoSize = TextFieldAutoSize.CENTER;
				technology.width = 420;
				technology.wordWrap = true;
				technology.name = 'technology';
				technology.x = 0;
				descContainers[j].addChild(technology);
				
				var btVisit:MovieClip = new library.simpleBt;
				btVisit.buttonMode = true;
				var btLabelFormat:TextFormat = new TextFormat();
				btLabelFormat.color = 0xffffff;
				btLabelFormat.align = 'center';
				btLabelFormat.bold = true;
				btLabelFormat.font = 'Arial';
				btLabelFormat.size = 15;
				var btLabel:TextField = new TextField();
				btLabel.defaultTextFormat = btLabelFormat;
				btLabel.selectable = false;
				btLabel.mouseEnabled = false;
				btLabel.text = 'Visitar';
				btLabel.width = btLabel.textWidth + 5;
				btLabel.height = btLabel.textHeight + 5;
				btLabel.x = (btVisit.width - btLabel.width) / 2;
				btLabel.y = (btVisit.height - btLabel.height) / 2;
				btVisit.addChild(btLabel);
				btVisit.name = 'btVisit';
				btVisit.addEventListener(MouseEvent.MOUSE_OVER, btVisitOverHandler);
				btVisit.addEventListener(MouseEvent.CLICK, btVisitClickHandler);
				descContainers[j].addChild(btVisit);
			}
			
			sliderContainer = new MovieClip();
			var slider = new library.sliderContainer;
			point0 = slider.width / 2;
			limitPoint = slider.width / 4;
			chainLock = 0.0077 * slider.width;
			sliderContainer.addChild(slider);
			var detailsContainer:MovieClip = new MovieClip();
			detailsContainer.graphics.beginFill(0);
			detailsContainer.graphics.drawRect(0, 0, slider.width, 150);
			detailsContainer.graphics.endFill();
			detailsContainer.y = slider.y + slider.height;
			detailsContainer.name = 'detailsContainer';
			sliderContainer.addChild(detailsContainer);
			sliderContainer.y = 100;
			var prevButton:MovieClip = new library.prevBt;
			prevButton.buttonMode = false;
			prevButton.y = detailsContainer.y;
			prevButton.addEventListener(MouseEvent.CLICK, prevClickHandler);
			prevButton.alpha = 0.4;
			sliderContainer.addChild(prevButton);
			prevBt = prevButton;
			var nextButton:MovieClip = new library.nextBt;
			nextButton.buttonMode = true;
			nextButton.x = slider.width - nextButton.width;
			nextButton.y = detailsContainer.y;
			nextButton.addEventListener(MouseEvent.CLICK, nextClickHandler);
			sliderContainer.addChild(nextButton);
			nextBt = nextButton;
			
			for(var i:int = 0; i < library.portfolio.item.length(); i++){
				var item:XML = XML(library.portfolio.item[i]);
				
				var portItem:MovieClip = new MovieClip();
				portItem.graphics.lineStyle(1, 0xffffff);
				portItem.graphics.beginFill(0xe7e7e7);
				portItem.graphics.drawRect(0, 0, 420, 330);
				portItem.graphics.endFill();
				portItem.filters = [shadowFilter];
				portItem.buttonMode = true;
				portItem.name = String(i);
				portItem.addEventListener(MouseEvent.CLICK, itemClickHandler);
				var itemLoading:MovieClip = new library.loadingGif;
				itemLoading.name = 'itemLoading';
				itemLoading.x = (portItem.width - itemLoading.width) / 2;
				itemLoading.y = (portItem.height - itemLoading.height) / 2;
				portItem.addChild(itemLoading);
				portItem.x = (i > 2 ? 1300 + 215 * i : portPositions[2 + i].x);
				portItem.y = (i > 2 ? 94.15 : portPositions[2 + i].y);
				sliderContainer.addChild(portItem);
				portfolioItens.push(portItem);
				
				var genericLoader:Loader = new Loader();
				genericLoader.load(new URLRequest('img/portfolio/' + String(item.thumb)));
				genericLoader.name = String(i);
				genericLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoadHandler);
			}
		}
		
		private function thumbLoadHandler(e:Event):void{
			var genericLoader:Loader = Loader(e.target.loader);
			genericLoader.x = 1;
			genericLoader.y = 1;
			
			portfolioItens[Number(genericLoader.name)].removeChild(portfolioItens[Number(genericLoader.name)].getChildByName('itemLoading'));
			portfolioItens[Number(genericLoader.name)].addChild(genericLoader);
			
			loadCounter++;
			if(loadCounter == 3){
				current = 0;
				portfolioItens[current].buttonMode = false;
				portfolioItens[current].removeEventListener(MouseEvent.CLICK, itemClickHandler);
				portfolioItens[current].addEventListener(MouseEvent.MOUSE_OVER, currentOverHandler);
				portfolioItens[current].addEventListener(MouseEvent.MOUSE_DOWN, onDown);
				
				var itemTitle:TextField = descContainers[0].getChildByName('title');
				itemTitle.text = library.portfolio.item[current].name;
				var itemDesc:TextField = descContainers[0].getChildByName('description');
				itemDesc.y = itemTitle.height;
				itemDesc.text = library.portfolio.item[current].desc;
				var itemTech:TextField = descContainers[0].getChildByName('technology');
				itemTech.y = itemDesc.y + itemDesc.height;
				itemTech.text = library.portfolio.item[current].tech;
				var btVisit:MovieClip = MovieClip(descContainers[0].getChildByName('btVisit'));
				btVisit.y = itemTech.y + itemTech.height + 5;
				btVisit.x = 158.75;
				
				this.removeChild(this.getChildByName('loadingGif'));
				setInterval(dimensioner, 0.01);
				this.addChild(sliderContainer);
				var detailsContainer:MovieClip = MovieClip(sliderContainer.getChildByName('detailsContainer'));
				descContainers[0].x = portPositions[2].x;
				descContainers[1].x = detailsContainer.width;
				detailsContainer.addChild(descContainers[0]);
				detailsContainer.addChild(descContainers[1]);
				descIdentifier = false;
			}
		}
		
		private function currentOverHandler(e:MouseEvent):void {
			portfolioItens[current].removeEventListener(MouseEvent.MOUSE_OVER, currentOverHandler);
			portfolioItens[current].addEventListener(MouseEvent.MOUSE_OUT, currentOutHandler);
			Mouse.cursor = 'hand';
		}
		
		private function currentOutHandler(e:MouseEvent):void {
			portfolioItens[current].addEventListener(MouseEvent.MOUSE_OVER, currentOverHandler);
			portfolioItens[current].removeEventListener(MouseEvent.MOUSE_OUT, currentOutHandler);
			Mouse.cursor = 'auto';
		}
		
		private function itemClickHandler(e:MouseEvent):void {
			switchItem(e.currentTarget.name);
		}
		
		private function onDown(e:MouseEvent):void {
			portfolioItens[current].removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
			portfolioItens[current].removeEventListener(MouseEvent.MOUSE_OUT, currentOutHandler);
			xDragOffset = mouseX - portfolioItens[current].x;
			this.root.addEventListener(MouseEvent.MOUSE_UP, onUp);
			this.root.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
		}
		
		private function onMove(e:MouseEvent):void {
			portfolioItens[current].x = mouseX - xDragOffset;
			
			var distanceFromPoint0:Number = point0 - (portfolioItens[current].x + portfolioItens[current].width / 2);
			distanceFromPoint0 = (distanceFromPoint0 < 0 ? -distanceFromPoint0 : distanceFromPoint0);
			
			if(distanceFromPoint0 >= (point0 - limitPoint) / 2){
				if(portfolioItens[current].x + portfolioItens[current].width / 2 < point0){
					portfolioItens[current].x = point0 - (point0 - limitPoint) / 2 - (portfolioItens[current].width / 2);
				} else if(portfolioItens[current].x + portfolioItens[current].width / 2 > point0){
					portfolioItens[current].x = point0 + (point0 - limitPoint) / 2 - (portfolioItens[current].width / 2);
				}
			}
			e.updateAfterEvent();
		}
		
		private function onUp(e:MouseEvent):void {
			this.root.removeEventListener(MouseEvent.MOUSE_UP, onUp);
			this.root.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
			xDragOffset = NaN;
			
			if(!isMouseOverArea(portfolioItens[current])){
				portfolioItens[current].addEventListener(MouseEvent.MOUSE_OVER, currentOverHandler);
				Mouse.cursor = 'auto';
			}
			
			e.updateAfterEvent();
			
			var distanceFromPoint0:Number = point0 - (portfolioItens[current].x + portfolioItens[current].width / 2);
			distanceFromPoint0 = (distanceFromPoint0 < 0 ? -distanceFromPoint0 : distanceFromPoint0);
			
			if(distanceFromPoint0 > (point0 - limitPoint) / 4){
				if(portfolioItens[current].x + portfolioItens[current].width / 2 < point0){
					if(current < portfolioItens.length - 1){
						switchItem(current + 1);
					} else{
						backItem();
					}
				} else if(portfolioItens[current].x + portfolioItens[current].width / 2 > point0){
					if(current > 0){
						switchItem(current - 1);
					} else{
						backItem();
					}
				}
			} else{
				if(distanceFromPoint0 != 0){
					backItem();
				} else{
					portfolioItens[current].addEventListener(MouseEvent.MOUSE_DOWN, onDown);
				}
			}
		}
		
		private function prevClickHandler(e:MouseEvent):void {
			prevBt.removeEventListener(MouseEvent.CLICK, prevClickHandler);
			nextBt.removeEventListener(MouseEvent.CLICK, nextClickHandler);
			portfolioItens[current].removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
			if(current > 0){
				switchItem(current - 1);
			} else{
				nextBt.addEventListener(MouseEvent.CLICK, nextClickHandler);
				prevBt.addEventListener(MouseEvent.CLICK, prevClickHandler);
				portfolioItens[current].addEventListener(MouseEvent.MOUSE_DOWN, onDown);
			}
		}
		
		private function nextClickHandler(e:MouseEvent):void {
			nextBt.removeEventListener(MouseEvent.CLICK, nextClickHandler);
			prevBt.removeEventListener(MouseEvent.CLICK, prevClickHandler);
			portfolioItens[current].removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
			if(current < portfolioItens.length - 1){
				switchItem(current + 1);
			} else{
				nextBt.addEventListener(MouseEvent.CLICK, nextClickHandler);
				prevBt.addEventListener(MouseEvent.CLICK, prevClickHandler);
				portfolioItens[current].addEventListener(MouseEvent.MOUSE_DOWN, onDown);
			}
		}
		
		private function backItem():void {
			var backTween:Tween = new Tween(portfolioItens[current], 'x', None.easeNone, portfolioItens[current].x, portPositions[2].x, 0.1, true);
			backTween.addEventListener(TweenEvent.MOTION_FINISH, backMotionHandler);
			function backMotionHandler(ev:TweenEvent):void {
				portfolioItens[current].addEventListener(MouseEvent.MOUSE_DOWN, onDown);
			}
		}
		
		private function switchDescription(choice:int):void {
			var itemTitle:TextField = descContainers[(descIdentifier ? 0 : 1)].getChildByName('title');
			itemTitle.text = library.portfolio.item[choice].name;
			var itemDesc:TextField = descContainers[(descIdentifier ? 0 : 1)].getChildByName('description');
			itemDesc.y = itemTitle.height;
			itemDesc.text = library.portfolio.item[choice].desc;
			var itemTech:TextField = descContainers[(descIdentifier ? 0 : 1)].getChildByName('technology');
			itemTech.y = itemDesc.y + itemDesc.height;
			itemTech.text = library.portfolio.item[choice].tech;
			var btVisit:MovieClip = MovieClip(descContainers[(descIdentifier ? 0 : 1)].getChildByName('btVisit'));
			btVisit.y = itemTech.y + itemTech.height + 5;
			btVisit.x = 158.75;
			var detailsContainer:MovieClip = MovieClip(sliderContainer.getChildByName('detailsContainer'));
			
			var descCurrentOut:Tween = new Tween(descContainers[(descIdentifier ? 1 : 0)],
												 'x',
												 None.easeNone,
												 descContainers[(descIdentifier ? 1 : 0)].x,
												 (choice > current ? -descContainers[(descIdentifier ? 1 : 0)].width : detailsContainer.width),
												 0.1,
												 true);
			var nextDescIn:Tween = new Tween(descContainers[(descIdentifier ? 0 : 1)],
											 'x',
											 None.easeNone,
											 (choice > current ? -descContainers[(descIdentifier ? 0 : 1)].width : detailsContainer.width),
											 portPositions[2].x,
											 0.1,
											 true);
		}

		private function switchItem(choice:int):void {
			switchDescription(choice);
			var switchTween:Tween = new Tween(portfolioItens[current], 'x', None.easeNone, portfolioItens[current].x, portPositions[2 - (choice - current)].x, 0.1, true);
			switchTween.addEventListener(TweenEvent.MOTION_FINISH, switchMotionHandler);
			function switchMotionHandler(e:TweenEvent):void {
				portfolioItens[current].buttonMode = true;
				portfolioItens[current].addEventListener(MouseEvent.CLICK, itemClickHandler);
				portfolioItens[current].removeEventListener(MouseEvent.MOUSE_OVER, currentOverHandler);
				current = choice;
				portfolioItens[current].buttonMode = false;
				portfolioItens[current].removeEventListener(MouseEvent.CLICK, itemClickHandler);
				portfolioItens[current].addEventListener(MouseEvent.MOUSE_OVER, currentOverHandler);
				portfolioItens[current].x = portPositions[2].x;
				portfolioItens[current].addEventListener(MouseEvent.MOUSE_DOWN, onDown);
				prevBt.addEventListener(MouseEvent.CLICK, prevClickHandler);
				nextBt.addEventListener(MouseEvent.CLICK, nextClickHandler);
				prevBt.alpha = 1;
				nextBt.alpha = 1;
				prevBt.buttonMode = true;
				nextBt.buttonMode = true;
				if(current == 0){
					prevBt.alpha = 0.4;
					prevBt.buttonMode = false;
				} else if(current == portfolioItens.length - 1){
					nextBt.alpha = 0.4;
					nextBt.buttonMode = false;
				}
				if(isMouseOverArea(portfolioItens[current])){
					portfolioItens[current].addEventListener(MouseEvent.MOUSE_OUT, currentOutHandler);
					Mouse.cursor = 'hand';
				}
			}
		}
		
		private function dimensioner():void {
			for(var i:int = 0; i < portfolioItens.length; i++){
				if(i != current){
					var xMoveLock:Number = (i < current ? portfolioItens[i + 1].x - chainLock - portfolioItens[i].width : portfolioItens[i - 1].x + portfolioItens[i - 1].width + chainLock);
					portfolioItens[i].x = xMoveLock;
				}
				
				if(portfolioItens[i].x >= portPositions[1].x && portfolioItens[i].x <= portPositions[3].x){
					var distanceFromPoint0:Number = point0 - (portfolioItens[i].x + portfolioItens[i].width /2);
					distanceFromPoint0 = (distanceFromPoint0 < 0 ? -distanceFromPoint0 : distanceFromPoint0);
					
					var scaleRelation:Number = (distanceFromPoint0 * 0.51) / (point0 - limitPoint);
					var yCoordinateRelation:Number = (portPositions[1].y - portPositions[2].y) / (point0 - limitPoint);
					
					
					portfolioItens[i].y = portPositions[2].y + distanceFromPoint0 * yCoordinateRelation;
					portfolioItens[i].scaleX = 1 - scaleRelation;
					portfolioItens[i].scaleY = 1 - scaleRelation;
				} else{
					portfolioItens[i].scaleX = 0.49;
					portfolioItens[i].scaleY = 0.49;
					portfolioItens[i].y = portPositions[1].y;
				}
			}
		}
		
		private function btVisitOverHandler(e:MouseEvent):void {
			e.currentTarget.removeEventListener(MouseEvent.MOUSE_OVER, btVisitOverHandler);
			var colorTransform:ColorTransform = new ColorTransform(0.7, 0.7, 0.7);
			e.currentTarget.transform.colorTransform = colorTransform;
			e.currentTarget.addEventListener(MouseEvent.MOUSE_OUT, btVisitOutHandler);
		}
		
		private function btVisitOutHandler(e:MouseEvent):void {
			e.currentTarget.removeEventListener(MouseEvent.MOUSE_OUT, btVisitOutHandler);
			var colorTransform:ColorTransform = new ColorTransform(1, 1, 1);
			e.currentTarget.transform.colorTransform = colorTransform;
			e.currentTarget.addEventListener(MouseEvent.MOUSE_OVER, btVisitOverHandler);
		}
		
		private function btVisitClickHandler(e:MouseEvent):void {
			var req:URLRequest = new URLRequest(String(library.portfolio.item[current].link));
			navigateToURL(req, '_blank');
		}

		private function isMouseOverArea(target:Object):Boolean {
			var answer:Boolean = false;
		
			if(mouseX >= target.x && mouseX <= (target.width + target.x)){
				if(mouseY >= target.y && mouseY <= (target.height + target.y)){
					answer = true;
				}
			}
			return answer;
		}
	}
}